package com.lookme.lmtool.utils;

import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * JAVA脚本处理类
 * @author blake
 */
public class JexlUtils {
    final static JexlEngine engine ;

    static{
        engine=new JexlEngine();
    }

    public static <T> T format(String text, Map<String,Object> params){
        if(StringUtils.isNotEmpty(text)) {
            params.put("Long",Long.class);
            params.put("Integer",Integer.class);
            params.put("String",String.class);
            params.put("Double",Double.class);
            params.put("Bool",Boolean.class);
            params.put("Float",Float.class);
            params.put("Byte",Byte.class);
            JexlContext context = new MapContext(params);
            Object execute = engine.createScript(text).execute(context);
            if (execute != null) {
                return (T)execute;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String template="Long.parseLong(amount)";

        Map<String,Object> params=new HashMap<>();
        params.put("msgType",0);
        params.put("amount","000000000010");
        params.put("content","test");
        params.put("out",System.out);
        params.put("Long",Long.class);
        System.out.println(""+format(template,params));
    }
}
